package com.woniuxy.happylife.datastore.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.woniuxy.happylife.datastore.config.OssCloudConfig;
import com.woniuxy.happylife.datastore.dao.ActivityReleaseDao;
import com.woniuxy.happylife.datastore.dao.UserDynamicDao;
import com.woniuxy.happylife.datastore.service.StoreService;
import com.woniuxy.happylife.datastore.util.StringUtil;
import com.woniuxy.happylife.entity.ActivityRelease;
import com.woniuxy.happylife.entity.UserDynamic;
import org.assertj.core.internal.Urls;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StoreServiceImpl implements StoreService {

    // 七牛文件上传管理器
    private UploadManager uploadManager;
    private String token;
    // 七牛认证管理
    private Auth auth;

    /**
     * 注入qiniu配置
     */
    @Resource
    OssCloudConfig ossCloudConfig;

    /**
     * 注入redis
     */
    @Resource
    RedisTemplate redisTemplate;

    /**
     * 注入dao
     */
    @Resource
    ActivityReleaseDao activityReleaseDao;
    @Resource
    UserDynamicDao userDynamicDao;

    /**
     * 上传文件至七牛云，保存活动数据到数据库
     * @param fileName
     * @param file
     * @return
     */
    @Override
    public boolean saveRelease(String fileName,MockMultipartFile file) {
        //配置七牛云
        qiniu();
        //从redis获取活动数据
        HashOperations hashOperations = redisTemplate.opsForHash();
        ActivityRelease activity = (ActivityRelease) hashOperations.get(file.getOriginalFilename(), "activity");
        hashOperations.delete(file.getOriginalFilename(), "activity");
        //上传文件到七牛云
        try {
            //得到远程oss图片地址
            String url = uploadQiniu(file);
            System.out.println(url);
            //将活动数据存入数据库
            if (url != null){
                activity.setReleasePhotoUrl(url);
                int i = activityReleaseDao.addActivity(activity);
                if(i != 0){
                    return true;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 上传文件至七牛云，保存动态数据到数据库
     * @param DynamicUuidStr
     * @param file
     * @return
     */
    @Override
    public String saveDynamic(String DynamicUuidStr, MultipartFile file) {
        //配置七牛云
        qiniu();
        HashOperations hashOperations = redisTemplate.opsForHash();
        //获取上一个图片地址
        String urls = (String) hashOperations.get(DynamicUuidStr, "urls");
        //获取需要上传图片的总个数
        Integer photoNumber = (Integer) hashOperations.get(DynamicUuidStr, "photoNumber");
        Long photoNumberLong = Long.parseLong(photoNumber.toString());
            try {
                String url = uploadQiniu(file);
                if (url != null){
                    hashOperations.delete(DynamicUuidStr, "urls");
                    //拼接多图地址
                    hashOperations.put(DynamicUuidStr, "urls", urls + url + ";");
                    //已经上传图片个数+1
                    Long alreadyUpload = hashOperations.increment(DynamicUuidStr, "alreadyUpload", 1);
                    //判断是否已经全部上传完毕
                    if(alreadyUpload == photoNumberLong){
                        //取出动态数据与所有图片url
                        UserDynamic userDynamic = (UserDynamic) hashOperations.get(DynamicUuidStr, "data");
                        String allUrl = (String) hashOperations.get(DynamicUuidStr, "urls");
                        userDynamic.setDynamicPhotoUrl(allUrl);
                        //调用dao存储用户动态数据
                        int i = userDynamicDao.addUserDynamic(userDynamic);
                        if(i != 0){
                            return "多图动态存储成功[" + DynamicUuidStr + "]:"+url;
                        }
                    }else {
                        return "多图上传中[" + DynamicUuidStr +"]:"+ url;
                    }
//
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        return "动态保存失败";
    }


    /**
     * 七牛云上传管理配置
     */
    public void qiniu(){
        // 构造一个带指定Zone对象的配置类, zone根据仓库地址
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        auth = Auth.create(ossCloudConfig.getQiniuAccessKey(), ossCloudConfig.getQiniuSecretKey());
        // 根据命名空间生成的上传token
        token = auth.uploadToken(ossCloudConfig.getQiniuBucketName());
    }

    /**
     * 文件上传七牛云返回远程地址
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadQiniu(MultipartFile file) throws IOException {
        // 使用工具类根据上传文件生成唯一图片名称
        String imgName = StringUtil.getRandomImgName(file.getOriginalFilename());
        //上传oss
        InputStream inputStream = file.getInputStream();
        Response put = uploadManager.put(inputStream, imgName, token, null, null);
        if (!put.isOK()) {
            throw new RuntimeException("上传七牛出错：" + put.toString());
        }
        // 解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(put.bodyString(), DefaultPutRet.class);
        String path = ossCloudConfig.getQiniuDomain() + "/" + putRet.key;
        // 这个returnPath是获得到的外链地址,通过这个地址可以直接打开图片
        return path;

    }
}
